package cn.schoolwow.quickdao.test.module.business.user.dml.userRole.flow.delete;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.transaction.Transaction;
import cn.schoolwow.quickdao.test.entity.Role;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickdao.test.entity.UserRole;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.junit.Assert;

public class DeleteUserRoleFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DAO dao = flowContext.checkInstanceData(DAO.class);

        dao.startTransaction(transaction -> {
            flowContext.putCurrentFlowData("transaction", transaction);
            deleteUserRole(flowContext);
            deleteUser(flowContext);
            deleteRole(flowContext);
        });
    }

    @Override
    public String name() {
        return "删除用户角色表流程";
    }

    private void deleteUserRole(FlowContext flowContext){
        Transaction transaction = (Transaction) flowContext.checkData("transaction");
        User insertUser = (User) flowContext.checkData("insertUser");
        Role insertRole = (Role) flowContext.checkData("insertRole");

        int effect = transaction.query(UserRole.class)
                .addQuery("userId", insertUser.getId())
                .addQuery("roleId", insertRole.getId())
                .execute()
                .delete();
        Assert.assertEquals(1, effect);
    }

    private void deleteUser(FlowContext flowContext){
        Transaction transaction = (Transaction) flowContext.checkData("transaction");
        User insertUser = (User) flowContext.checkData("insertUser");

        int effect = transaction.query(User.class)
                .addQuery("id", insertUser.getId())
                .execute()
                .delete();
        Assert.assertEquals(1, effect);
    }

    private void deleteRole(FlowContext flowContext){
        Transaction transaction = (Transaction) flowContext.checkData("transaction");
        Role insertRole = (Role) flowContext.checkData("insertRole");

        int effect = transaction.query(Role.class)
                .addQuery("id", insertRole.getId())
                .execute()
                .delete();
        Assert.assertEquals(1, effect);
    }
}
